import logging

from django.db import DatabaseError
from django.http.response import JsonResponse
from django.middleware.common import MiddlewareMixin

from common.enums.status_code_enum import StatusCodeEnum
from common.responses.r import R
from config.exception.common_exception import BusinessException, BaseDatabaseError

logger = logging.getLogger('django')


class ExceptionMiddleware(MiddlewareMixin):
    """统一异常处理中间件"""

    def process_exception(self, request, exception):
        """
        统一异常处理
        :param request: 请求对象
        :param exception: 异常对象
        :return:
        """
        if isinstance(exception, BusinessException):
            # 业务异常处理
            data = R.set_result(exception.enum_cls)
            return JsonResponse(data)

        elif isinstance(exception, BaseDatabaseError):
            # 数据库异常
            r = R.set_result(StatusCodeEnum.DB_ERR)
            logger.error(r, exc_info=True)
            return JsonResponse(r)

        elif isinstance(exception, Exception):
            # 服务器异常处理
            r = R.server_error()
            logger.error(r, exc_info=True)
            return JsonResponse(r)

        return None

